package com.Jiang.servlet.User;
import com.Jiang.pojo.Role;
import com.Jiang.pojo.User;
import com.Jiang.service.Role.RoleService;
import com.Jiang.service.Role.RoleServiceImplements;
import com.Jiang.service.User.UserService;
import com.Jiang.service.User.UserServiceImplements;
import com.Jiang.utillity.Constants;
import com.alibaba.fastjson.JSONArray;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

//复用型
public class UserServlet extends HttpServlet {
    private UserService userService;
    private RoleService roleService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        userService = new UserServiceImplements();
        roleService = new RoleServiceImplements();
        if (method.equals("savepwd")) {
            try {
                ModifyPassword(req, resp);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else if (method.equals("pwdmodify")) {
            CheckPassword(req, resp);
        } else if (method.equals("query")) {
            try {
                query(req, resp);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else if (method.equals("add")) {
            try {
                add(req, resp);
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else if (method.equals("ucexist")) {
            try {
                ucexist(req, resp);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else if (method.equals("getrolelist")) {
            try {
                getrolelist(req, resp);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else if (method.equals("view")) {
            try {
                view(req, resp);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else if (method.equals("modify")) {
            try {
                modify(req, resp);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        else if(method.equals("modifyexe")){
            try {
                modifyexe(req, resp);
            } catch (SQLException | ParseException e) {
                e.printStackTrace();
            }
        }
        else if(method.equals("deluser")){
            try {
                deluser(req, resp);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    //修改密码
    public void ModifyPassword(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        String newpassword = req.getParameter("newpassword");
        System.out.println("新的密码是:" + newpassword);
        User u = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        boolean flag = userService.ModifyPassword(u.getId(), newpassword);
        if (flag) {
            System.out.println("修改成功!");
            req.getSession().removeAttribute(Constants.USER_SESSION);
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
        } else {
            req.setAttribute("message", "这不可能修改失败");
        }
    }

    //修改密码中的AJAX验证密码
    public void CheckPassword(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        String updatePassword = req.getParameter("oldpassword");
        Map result = new HashMap();
        if (user == null)
            result.put("result", "sessionerror");
        else if (updatePassword == null || updatePassword.length() == 0)
            result.put("result", "error");
        else {
            String oldPassword = user.getUserPassword();
            if (oldPassword.equals(updatePassword))
                result.put("result", "true");
            else
                result.put("result", "false");
        }
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(result));
        writer.flush();
        writer.close();
    }

    //查询功能
    public void query(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException {
        System.out.println("开始查询!");
        //得到前端查询的用户名
        String queryUserName = req.getParameter("queryUserName");
        //System.out.println(queryUserName);
        //得到前端查询的角色名
        String qur = req.getParameter("queryUserRole");
        int queryUserRole = 0;
        if (qur != null && !qur.equals(""))
            queryUserRole = Integer.parseInt(qur);
        //获得当前的界面
        String cpn = req.getParameter("pageIndex");
        int currentPageNo = 1;
        if (cpn != null && !cpn.equals(""))
            currentPageNo = Integer.parseInt(cpn);

        //得到用户列表
        Vector userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, Constants.PageSize);
        //得到角色列表
        Vector roleList = roleService.getRoleList();
        //总记录数:
        int totalCount = userService.getUserCount(null, 0); //总人数
        //总页数:
        int totalPageCount = totalCount / Constants.PageSize + 1;
        //防止当前页面出界
        currentPageNo = currentPageNo < 1 ? 1 : currentPageNo;
        currentPageNo = currentPageNo > totalPageCount ? totalPageCount : currentPageNo;
        //System.out.println(currentPageNo);
        //设置属性
        req.setAttribute("queryUserName", queryUserName);
        req.setAttribute("queryUserRole", queryUserRole);
        req.setAttribute("userList", userList);
        req.setAttribute("roleList", roleList);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.getRequestDispatcher("userlist.jsp").forward(req, resp);
    }

    //添加用户
    public void add(HttpServletRequest req, HttpServletResponse resp) throws ParseException, SQLException, IOException, ServletException {
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");
        User use = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        int createdBy = use.getUserRole();
        Date creationDate = new Date();
        User user = new User();
        user.setId(null);
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setGender(Integer.parseInt(gender));
        user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.parseInt(userRole));
        user.setCreatedBy(createdBy);
        user.setCreationDate(new Date());
        user.setModifyby(null);
        user.setModifyDate(null);
        if (userService.addUser(user)) {
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
            System.out.println("成功");
        } else {
            req.getRequestDispatcher("useradd.jsp").forward(req, resp);
            System.out.println("失败");
        }
    }

    //添加用户中的AJAX用户编码验证
    public void ucexist(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        String userCode = req.getParameter("userCode");
        Map m = new HashMap();
        if (userCode == null || userCode.length() == 0) m.put("userCode", "exist");
        else {
            if (userService.FindUserCodeIsExist(userCode))
                m.put("userCode", "exist");
            else m.put("userCode", "notexist");
        }
        resp.setContentType("application/json");
        PrintWriter printWriter = resp.getWriter();
        printWriter.write(JSONArray.toJSONString(m));
        printWriter.flush();
        printWriter.close();
    }

    //添加用户中的AJAX角色列表获取
    public void getrolelist(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        Vector result = roleService.getRoleList();
        resp.setContentType("application/json");
        PrintWriter printWriter = resp.getWriter();
        printWriter.write(JSONArray.toJSONString(result));
        printWriter.flush();
        printWriter.close();
    }

    public void view(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        int id = Integer.parseInt(req.getParameter("uid"));
        User user = userService.getUserById(id);
        if (user != null) {
            req.setAttribute("user", user);
            req.getRequestDispatcher("userview.jsp").forward(req, resp);
        }
    }

    public void modify(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("uid"));
        User user = userService.getUserById(id);
        if (user != null) {
            req.setAttribute("user", user);
            req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
        }
    }

    public void modifyexe(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException, ParseException {
        int id = Integer.parseInt(req.getParameter("uid"));
        User user = new User();
        user.setId(id);
        user.setUserName(req.getParameter("userName"));
        user.setGender(Integer.parseInt(req.getParameter("gender")));
        user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(req.getParameter("birthday")));
        user.setPhone(req.getParameter("phone"));
        user.setAddress(req.getParameter("address"));
        user.setUserRole(Integer.parseInt(req.getParameter("userRole")));

        User Nowuser=(User)req.getSession().getAttribute(Constants.USER_SESSION);
        int modifyBy=Nowuser.getId();
        if(userService.modifyUser(user,modifyBy)){
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
        }else
            req.getRequestDispatcher("usermodify.jsp").forward(req,resp);
    }

    public void deluser(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException {
        Map result=new HashMap();
        int id=Integer.parseInt(req.getParameter("uid"));
        if(userService.deluser(id))
        result.put("delResult","true");
        else
        result.put("delResult","false");

        PrintWriter writer = resp.getWriter();
        resp.setContentType("application/json");
        writer.write(JSONArray.toJSONString(result));
        writer.flush();
        writer.close();

    }
}
